<template>
	<view class="pageview">
		<cl-navbar leftIconSize="40rpx" placeholder usericon friendicon>
			<view class="navtitleview" slot="center" @click="reconnect">
				<text>{{isConnected?$t('index.index.title2'):reconnectCount<5? $t("socket.index.reconnection")+'.'.repeat(reconnectCount+1):$t("socket.index.unconnected")}}</text>
				<u-icon name="/static/shuaxin.png" size="14" style="margin-left: 5rpx;"
					v-show="!isConnected && reconnectCount>=5"></u-icon>
			</view>
		</cl-navbar>


		<view class="searchview">
			<u-search :inputStyle="{fontSize:'24rpx'}" :showAction="false" height="64rpx" :clearabled="false"
				bgColor="#ffffff" :placeholder="$t('commonality.search')" @input="searchInput"></u-search>
		</view>

		<view class="listview">
			<u-list height="100%" :scrollIntoView="scrollToId">
				<uni-swipe-action ref="swipeAction">
					<!-- <u-swipe-action> -->
					<!-- 置顶 -->
					<view style="border-radius: 40rpx;overflow: hidden;">
						<u-list-item>
							<view class="listitemtop" @click="gopage('friend_apply')">
								<view class="listitem__left" style="width: 100rpx;height: 100rpx;">
									<image style="width: 90rpx;height: 90rpx;margin-left: 5rpx;margin-top: 5rpx;"
										src="/static/icon/newfriend.svg"></image>
								</view>
								<view class="listitem__right">
									<view class="listitem__right__top">
										<view class="listitem__right__top__nickname">
											<text>{{$t("addressbook.friend_apply.title")}}</text>
										</view>
										<u-badge type="error" :value="newFriendCount" :max="99"
											:customStyle="{fontSize:'20rpx'}"></u-badge>
									</view>
								</view>
							</view>
						</u-list-item>
						<template v-for="(item, index) in getList">
							<uni-swipe-action-item :id="'chat'+item.chat_id" :right-options="getOption(item)"
								@click="pickerMenu" :key="item.chat_type+item.chat_id" v-if="item.is_top">
								<!-- <u-swipe-action-item :options="getOption(item)" @click="pickerMenu" :key="item.chat_id" v-if="item.is_top"> -->
								<u-list-item>
									<view class="listitemtop" :data-item="item" @click="gochatMsg(item)">
										<view class="listitem__left">
											<cl-avatar :src="item.chat_face" size="100rpx"
												:key="item.chat_face+item.chat_id"></cl-avatar>
										</view>
										<view class="listitem__right">
											<view class="listitem__right__top">
												<view class="listitem__right__top__nickname">
													<text class="u-line-1">{{item.chat_name}}</text>
													<text v-if="item.tags && item.tags != 'null' && item.tags != 'undefined'" class="typetag"
														:style="{backgroundColor: item.tags_font_color || ''}">{{item.tags}}</text>
													<text v-if="item.chat_type=='group'" class="typetag"
														style="background-color: #52AAFF;">{{$t('index.index.group')}}</text>
													<text
														v-if="item.chat_member_type && item.chat_member_type > 0 && item.chat_member_type != 6 && item.chat_member_type != 8"
														class="typetag"
														style="background-color: #02D478;">{{$t('common.friend.authority')}}</text>
													<text class="typetag">{{$t('index.index.top')}}</text>
												</view>

												<text
													class="listitem__right__top__time">{{item.last_time|formatTime}}</text>
											</view>
											<view class="listitem__right__content"
												style="display: flex;justify-content: space-between;">
												<view style="display: flex;">
													<view v-if="item.chat_type == 'private'" style="display: flex;">
														<text v-if="friendOnline[item.chat_id]"
															style="color: #6aaf76;font-size: 24rpx;margin-right: 5rpx;">[{{$t('common.friend.online')}}]</text>
														<text v-else
															style="color: #595A66;font-size: 24rpx;margin-right: 5rpx;">[{{$t('common.friend.offline')}}]</text>
													</view>
													<text v-if="item.chat_type == 'group' && item.at == 1"
														style="color: #f56c6c;font-size: 24rpx;margin-right: 5rpx;">
														[{{$t("index.index.atYou")}}]
													</text>
													<rich-text :nodes="msgDetails(item)" :selectable="false"
														style="white-space: pre-wrap;"
														class="listitem__right__content__msg u-line-1"></rich-text>
												</view>
												<view style="display: flex;align-items: center;gap: 10rpx;">
													<view v-if="item.unread_count">
														<u-badge type="error" :value="item.unread_count" :max="99"
															:isDot="item.disturbing == '1'?true:false"
															:customStyle="{fontSize:'20rpx'}"></u-badge>
													</view>
													<u-icon name="/static/icon/chatmiandarao.svg" size="30rpx"
														v-if="item.disturbing"></u-icon>
												</view>
											</view>
										</view>
									</view>
								</u-list-item>
							</uni-swipe-action-item>
						</template>
					</view>
					<!-- 非置顶 -->
					<template v-for="(item, index) in getList">
						<uni-swipe-action-item :id="'chat'+item.chat_id" :right-options="getOption(item)"
							@click="pickerMenu" :key="item.chat_type+item.chat_id" v-if="!item.is_top">
							<!-- <u-swipe-action-item :options="getOption(item)" @click="pickerMenu" :key="item.chat_id" v-if="!item.is_top"> -->
							<u-list-item>
								<view class="listitem" :data-item="item" @click="gochatMsg(item)">
									<view class="listitem__left">
										<cl-avatar :src="item.chat_face" size="100rpx"
											:key="item.chat_face+item.chat_id"></cl-avatar>
									</view>
									<view class="listitem__right" style="align-self: self-start;">
										<view class="listitem__right__top">
											<view class="listitem__right__top__nickname">
												<text class="u-line-1">{{item.chat_name}}</text>
												<text v-if="item.tags && item.tags != 'null' && item.tags != 'undefined'" class="typetag"
													:style="{backgroundColor: item.tags_font_color || ''}">{{item.tags}}</text>
												<text v-if="item.chat_type=='group'" class="typetag"
													style="background-color: #52AAFF;">{{$t('index.index.group')}}</text>
												<text
													v-if="item.chat_member_type && item.chat_member_type > 0 && item.chat_member_type != 6 && item.chat_member_type != 8"
													class="typetag"
													style="background-color: #02D478;">{{$t('common.friend.authority')}}</text>
											</view>
											<text
												class="listitem__right__top__time">{{item.last_time|formatTime}}</text>
										</view>
										<view class="listitem__right__content"
											style="display: flex;justify-content: space-between;">
											<view style="display: flex;">
												<view v-if="item.chat_type == 'private'" style="display: flex;">
													<text v-if="friendOnline[item.chat_id]"
														style="color: #6aaf76;font-size: 24rpx;margin-right: 5rpx;">[{{$t('common.friend.online')}}]</text>
													<text v-else
														style="color: #595A66;font-size: 24rpx;margin-right: 5rpx;">[{{$t('common.friend.offline')}}]</text>
												</view>
												<text v-if="item.chat_type == 'group' && item.at == 1"
													style="color: #f56c6c;font-size: 24rpx;margin-right: 5rpx;">
													[{{$t("index.index.atYou")}}]
												</text>
												<rich-text :nodes="msgDetails(item)" :selectable="false"
													style="-webkit-touch-callout: none;white-space: pre-wrap;overflow: hidden;text-overflow: ellipsis;"
													class="listitem__right__content__msg u-line-1"></rich-text>
											</view>
											<view style="display: flex;align-items: center;gap: 10rpx;">
												<view v-if="item.unread_count">
													<u-badge type="error" :value="item.unread_count" :max="99"
														:isDot="item.disturbing == '1'?true:false"
														:customStyle="{fontSize:'20rpx'}"></u-badge>
												</view>
												<u-icon name="/static/icon/chatmiandarao.svg" size="30rpx"
													v-if="item.disturbing"></u-icon>
											</view>
										</view>
									</view>
								</view>
							</u-list-item>
						</uni-swipe-action-item>
					</template>
				</uni-swipe-action>
			</u-list>
		</view>
		<view>
			<u-popup :show="deleteJson.show" @close="deleteJson.show = false" bgColor="transparent">
				<view style="display: flex;flex-direction: column;align-items: center;padding-bottom: 20rpx;">
					<view
						style="border: #d68e5f solid 1rpx;box-sizing: border-box;display: flex;flex-direction: column;border-radius: 15rpx;align-items: center;text-align: center;background-color: #ffffff;width: 720rpx;">
						<view style="padding: 40rpx" v-if="deleteJson.data">
							<cl-avatar :src="deleteJson.data.chat_face" size="100rpx"
								:key="deleteJson.data.chat_face+deleteJson.data.chat_id"></cl-avatar>
							<view style="margin-top: 20rpx; font-size: 30rpx;">
								{{ $t('chat.msg.confirmDeleteConversation', { chatName: deleteJson.data.chat_name }) }}
							</view>
						</view>
						<view
							style="padding: 30rpx;font-size: 30rpx;color: #fa5048;border-top: 1rpx solid #f8f8f8;width: 100%;text-align: center;box-sizing: border-box;"
							@click="deleteClick('my',deleteJson.data)">{{$t("index.index.deleteMySession")}}</view>
						<view v-if="getDelOtherMsg"
							style="padding: 30rpx;font-size: 30rpx;color: #fa5048;border-top: 1rpx solid #f8f8f8;width: 100%;text-align: center;box-sizing: border-box;"
							@click="deleteClick('all',deleteJson.data)">{{$t("index.index.deleteAllSession")}}</view>
					</view>
					<view @click="deleteJson.show = false" style="background-color: #ffffff;border-radius: 15rpx;width: 720rpx;margin-top: 20rpx;text-align: center;padding: 25rpx 0;font-size: 30rpx;">
						{{$t("common.cancelText")}}</view>
				</view>
			</u-popup>

			<u-popup :show="noticeData.show" @close="noticeData.show = false" bgColor="transparent" mode="center">
				<view style="display: flex;flex-direction: column;align-items: center;position: relative;">
					<image src="/static/gonggao/laba.png"
						style="width: 194rpx;height: 250rpx;position: absolute;top: -100rpx;right: 20rpx;z-index: 1;">
					</image>
					<image src="/static/gonggao/tou.png" mode="widthFix" style="width: 610rpx;display: block;"></image>
					<text style="position: absolute;top: 50rpx;left: 30rpx;font-size: 50rpx;color: #FFFFFF;font-weight: 500;max-width: 400rpx;">{{$t("index.index.sysbulletin")}}</text>
					<view class=""
						style="background: linear-gradient(180deg, #66a6ef 0%, #96c6fb 100%);width: 609rpx;border-radius: 0 0 40rpx 40rpx;margin-top: -10rpx;z-index: 1;">
						<view style="word-wrap: break-word;max-height: 40vh;overflow-y: auto;overflow-x: hidden;padding:0 20rpx;color: #FFFFFF;" v-html="systemBulletin">
						</view>
						<view @click="noticeData.show = false"
							style="background: #FFFFFF;box-shadow: 0 3px 0 0 rgba(0,0,0,0.10);width: 360rpx;height: 100rpx;line-height: 100rpx;margin: 40rpx auto;border-radius: 25px;text-align: center;font-size: 40rpx;color: #549AEA;font-weight: 500;">
							{{$t("index.index.know")}}
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<!-- <cl-tabbar :currentTab="0" @click="tabbarClick"></cl-tabbar> -->
	</view>
</template>

<script>
	import sqliteSeesion from '@/sqlite_services/seesion.js'
	import msgSqlite from "@/sqlite_services/msg.js"
	import $T from '@/common/tools/time.js';
	import {
		mapState
	} from 'vuex'
	import {
		replaceEmojis
	} from '@/components/cl-chat-input/o-emoji/emoji.js';
	import sqliteGroup from '@/sqlite_services/group.js'
	import friendSqlite from '@/sqlite_services/friend.js'
	export default {
		name: 'index',
		data() {
			return {
				searchval: '',
				scrollToId: '',
				deleteJson: {
					show: false,
					data: null
				}, //删除信息

				noticeData: {
					show: false,
					content: '',
				},
				systemBulletin:'',
			};
		},
		filters: {
			formatTime(value) {
				if (!value) return ''
				return $T.gettime(value);
			},
		},
		computed: {
			...mapState({
				user_info: state => state.user.user_info,
				plat_info: state => state.plat.plat_info,
				sessionList: state => state.session.sessionList,
				friendOnline: state => state.friends.friendOnline,
				isConnected: state => state.isConnected,
				reconnectCount: state => state.reconnectCount,
				newFriendCount: state => state.tabbarbadge.newFriendCount,
			}),
			getDelOtherMsg() {
				if (!this.plat_info) return false
				// (0:所有人;1:普通用户;2后台用户,3都不允许)
				if (this.plat_info.del_p_msg == '0') {
					return true
				} else if (this.plat_info.del_p_msg == '1') {
					if (this.user_info.user_type == '0') return true
				} else if (this.plat_info.del_p_msg == '2') {
					if (this.user_info.user_type > 0) return true
				}
				return false
			},
			getOption() {
				return (item) => {
					return [{
						key: item.is_top ? 'untop' : 'top',
						text: item.is_top ? this.$t('index.index.untop') : this.$t('index.index.topChat'),
						style: {
							backgroundColor: '#3c9cff',
							fontSize: '13px',
						},
						item
					}, {
						key: 'disturbing',
						text: item.disturbing ? this.$t('chat.msg.notification.enable') : this.$t(
							'chat.msg.notification.doNotDisturb'),
						style: {
							backgroundColor: '#ffaa00',
							fontSize: '13px'
						},
						item
					}, {
						key: 'delete',
						text: this.$t('index.index.deleteChat'),
						style: {
							backgroundColor: '#f56c6c',
							fontSize: '13px'
						},
						double: item.chat_type != 'private',
						item
					}]
				}
			},
			getList() {
				let newdata = this.sessionList.filter(item => {
					// 根据名字筛选
					if (this.searchval && item.chat_name.indexOf(this.searchval) === -1) {
						return false;
					}
					return true;
				});
				return newdata
			},
			msgDetails() {
				return (item) => {
					switch (item.last_msg_type) {
						case 'text':
							const parsedContent = JSON.parse(item.last_msg)?.[0]?.text?.content;
							const content = parsedContent !== undefined ? parsedContent : item.last_msg;
							return replaceEmojis(content, '12px')
							break;
						case 'image':
							return `[${this.$t('chat.msg.type.image')}]`
							break;
						case 'video':
							return `[${this.$t('chat.msg.type.video')}]`
							break;
						case 'audio':
							return `[${this.$t('chat.msg.type.audio')}]`
							break;
						case 'd_r':
							return `[${this.$t('chat.msg.type.dice')}]`
							break;
						case 'video_call':
							return `[${this.$t('chat.msg.type.videoCall')}]`
							break;
						case 'voice_call':
							return `[${this.$t('chat.msg.type.voiceCall')}]`
							break;
						case 'r_p':
							const r_qContent = JSON.parse(item.last_msg)?.[0]?.r_p?.remark;
							return [{
									name: 'span',
									attrs: {
										style: 'color: red;'
									},
									children: [{
										type: 'text',
										text: `[${this.$t('chat.msg.type.r_p')}]`
									}]
								},
								{
									name: 'span',
									children: [{
										type: 'text',
										text: r_qContent || this.$t("chat.msg.redPacket.defaultMessage")
									}]
								}
							];
							return `[${this.$t('chat.msg.type.r_p')}]`
							break;
						case 'b_c':
							return `[${this.$t('chat.msg.type.b_c')}]`
							break;
						case 'mixed':
							return `[${this.$t('chat.msg.type.mixed')}]`
							break;
						case 'sys_notice':
							const sysparsedContent = JSON.parse(item.last_msg)?.[0]?.text?.content;
							return sysparsedContent !== undefined ? sysparsedContent : item.last_msg;
							break;
						default:
							return ""
							break;
					}
				}
			}
		},
		onLoad() {
			console.log(this.sessionList);
			// disturbing
			// uni.hideTabBar()
			this.$api.common.noticeList().then(res=>{
				if(res && res.data && res.data.length){
					this.systemBulletin = res.data[0].content
					this.noticeData.show = true
				}
			})
		},
		methods: {
			tabbarClick(e) {
				this.reconnect()
				this.scrollToUnreadConversation()
			},
			scrollToUnreadConversation() {
				const unreadConversation = this.getList.find(item => item.unread_count > 0 && !item.disturbing);
				if (unreadConversation) {
					// setTimeout(()=>{
					// 	this.scrollToId = '';
					// },10)
					this.scrollToId = 'chat' + unreadConversation.chat_id;
					this.$nextTick(() => {
						this.scrollToId = '';
					})
				}
			},
			searchInput(e) {
				uni.$u.debounce(() => {
					this.searchval = e
				}, 500, false)
			},
			gopage(name) {
				this.$Router.push({
					name
				});
			},
			gochatMsg(item) {
				console.log(item);
				if (item.chat_type == 'private') {
					this.$Router.push({
						name: 'chatMsg',
						params: {
							friend_idx: item.chat_id,
							nick_name: item.chat_name,
							avatar_url: item.chat_face,
							user_type: item.chat_member_type
							// screen:true
						}
					});
				} else {
					this.$Router.push({
						name: 'chatGroupMsg',
						params: {
							group_id: item.chat_id,
							group_name: item.chat_name,
							avatar_url: item.chat_face,
						}
					});
				}
			},
			//删除会话私聊的
			deleteClick(type, data) {
				this.deleteJson.show = false
				if (type == 'all') {
					uni.$api.chat.delMutualMsg({
						target_id: data.chat_id,
						conversation_id: data.conversation_id
					}).then(res => {
						if (res.code == 200) {
							this.$store.dispatch('removeSession', data.chat_id)
							msgSqlite.delMsgUserId(data.chat_id, data.chat_type)
						}
					})
				} else {
					this.$store.dispatch('removeSession', data.chat_id)
					msgSqlite.delMsgUserId(data.chat_id, data.chat_type)
				}

			},
			/* 选择菜单 */
			pickerMenu(e) {
				e = e.content
				let index = this.sessionList.findIndex(item => item.chat_id === e.item.chat_id)
				// this.$refs.swipeAction.closeAll()
				if (index != -1) {
					switch (e.key) {
						//取消置顶
						case 'untop':
							this.$store.dispatch('updateSession', {
								chat_id: e.item.chat_id,
								data: {
									is_top: 0
								}
							})
							break;
							//置顶
						case 'top':
							this.$store.dispatch('updateSession', {
								chat_id: e.item.chat_id,
								data: {
									is_top: 1
								}
							})
							break;
						case 'delete':
							if (e.item.chat_type == 'group') {
								this.$store.dispatch('removeSession', e.item.chat_id)
								msgSqlite.delMsgUserId(e.item.chat_id, e.item.chat_type)
							} else if (e.item.chat_type == 'private') {
								this.deleteJson.show = true
								this.deleteJson.data = e.item
							}
							break;
						case 'disturbing':
							//这里需要更新用户表和会话表
							let upval = e.item.disturbing
							if (upval) {
								upval = 0
							} else {
								upval = 1
							}
							let data = {
								disturbing: upval,
							}
							this.$store.dispatch('updateSession', {
								chat_id: e.item.chat_id,
								data
							})
							if (e.item.chat_type == 'group') {
								sqliteGroup.editGroupInfo(e.item.chat_id, data)
							} else if (e.item.chat_type == 'private') {
								friendSqlite.editUserInfo(e.item.chat_id, data)
							}
							break;
						default:
							break;
					}
				}
			},
			//重连
			reconnect() {
				//这里调用重连
				if (!this.isConnected && this.reconnectCount >= 5) {
					this.$store.state.user.socket.activeReconnect()
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	// ::v-deep {
	// 	.u-navbar--fixed{
	// 		border-bottom: 1rpx solid #e2e2e2;
	// 	}
	// }
	.navtitleview {
		display: flex;
		align-items: center;
		font-size: 15px;

		&__memeber {
			font-size: 26rpx;
			color: #61626e;
		}
	}

	.typetag {
		white-space: nowrap;
		font-size: 20rpx;
		color: #FFFFFF;
		padding: 0 10rpx;
		height: 28rpx;
		line-height: 28rpx;
		text-align: center;
		border-radius: 10rpx;
		background-color: #FF7676;
	}

	.searchview {
		margin: 20rpx 30rpx;
		background-color: #ffffff;
		border-radius: 60rpx;
		padding-right: 20rpx;
	}

	.listview {
		flex: 1;
		overflow: hidden;

		.listitemtop,
		.listitem {
			display: flex;
			align-items: center;
			padding: 20rpx 20rpx;
			position: relative;

			&.active {
				background-color: #ffffff;
			}

			&.listitemtop::after {
				content: "";
				position: absolute;
				width: calc(100% - 140rpx);
				background-color: #ebebeb;
				height: 0.5rpx;
				bottom: 0;
				right: 0;
			}

			&.listitem::after {
				content: "";
				position: absolute;
				width: calc(100% - 140rpx);
				background-color: #e1e1e1;
				height: 0.5rpx;
				bottom: 0;
				right: 0;
			}

			&__left {
				width: 100rpx;
				height: 100rpx;
			}

			&__right {
				margin-left: 20rpx;
				flex: 1;
				min-width: 0;

				&__top {
					display: flex;
					justify-content: space-between;
					align-items: center;

					&__nickname {
						max-width: 500rpx;
						color: #333333;
						font-size: 28rpx;
						display: flex;
						align-items: center;
						gap: 10rpx;
					}

					&__time {
						color: #61626E;
						font-size: 20rpx;
					}
				}

				&__content {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 15rpx;

					&__msg {
						flex: 1;
						font-size: 24rpx;
						color: #595A66;
					}
				}
			}
		}

		.listitemtop {
			background-color: #ffffff;
		}

		.listitem {
			background-color: #ededed;
		}
	}

	/* 遮罩 */
	.shade {
		position: fixed;
		z-index: 100;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;

		.pop {
			position: fixed;
			z-index: 101;
			width: 200rpx;
			box-sizing: border-box;
			font-size: 28rpx;
			text-align: left;
			color: #ffffff;
			background-color: #ffffff;
			box-shadow: 0 0 5rpx rgba(255, 255, 255, 0.5);
			line-height: 80rpx;
			transition: transform 0.1s ease-in-out 0s;
			user-select: none;
			transform: scale(0, 0);

			&.show {
				transform: scale(1, 1);
			}

			&>view {
				padding: 0 20rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				user-select: none;

				// &:active {
				// 	background-color: #f3f3f3;
				// }
			}
		}
	}

	.cellviewGrop {
		.cellview {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;

			&__left {
				display: flex;
				align-items: center;

				&__img {
					width: 70rpx;
					height: 70rpx;
					border-radius: 20rpx;
				}

				&__title {
					font-size: 28rpx;
					margin-left: 20rpx;
					color: #FFFFFF;
				}
			}
		}
	}
</style>